#include "encrypter.h"
#include <cstring>
#include <cctype>

encrypter::encrypter()
{
	ascInput = 0;
	ascKey   = 0;
	output   = 0;
}

encrypter::~encrypter()
{
	delete [] output;
}

char* encrypter::encrypt(char* input, char* key)
{
	mapToAscii(input, key);
	if (output != 0){delete [] output; output = 0;}
	output = new char[inputLength + 1];
	
	for (int i = 0, j = 0; i < inputLength; i++, j++)
	{
		if (j >= keyLength) j = 0;
		if (((ascInput[i] + ascKey[j]) % 36) > 25)
			output[i] = tolower(((ascInput[i] + ascKey[j]) % 36) + 22);
		else
			output[i] = tolower(((ascInput[i] + ascKey[j]) % 36) + 65);
	}

	output[inputLength] = '\0';
	delete [] ascInput; ascInput = 0;
	delete [] ascKey;   ascKey   = 0;
	return output;
}

char* encrypter::decrypt(char* input, char* key)
{
	int value;
	mapToAscii(input, key);
	if (output != 0){delete [] output; output = 0;}
	output = new char[inputLength + 1];
	
	for (int i = 0, j = 0; i < inputLength; i++, j++)
	{
		if (j >= keyLength) j = 0;
		
		if (ascInput[i] - ascKey[j] < 0)
			value = 36 - (-(ascInput[i] - ascKey[j]));
		else
			value = ascInput[i] - ascKey[j];
		
		if (value > 25)
			output[i] = tolower(value + 22);
		else
			output[i] = tolower(value + 65);
	}

	output[inputLength] = '\0';
	delete [] ascInput; ascInput = 0;
	delete [] ascKey;   ascKey   = 0;
	return output;
}

void encrypter::mapToAscii(char* input, char* key) //Map the A-Z 0-9 to integer value, 0-35
{
	inputLength = strlen(input);
	keyLength   = strlen(key);
	ascInput = new int[inputLength];
	ascKey   = new int[keyLength];
	
	for (int i = 0; i < inputLength; i++)
	{
		if (int(input[i]) >= 48 && int(input[i]) <= 57)
			ascInput[i] = int(toupper(input[i])) - 22;
		else
			ascInput[i] = int(toupper(input[i])) - 65;
	}
	
	for (int i = 0; i < keyLength; i++)
	{
		if (int(key[i]) >= 48 && int(key[i]) <= 57)
			ascKey[i] = int(toupper(key[i])) - 22;
		else
			ascKey[i] = int(toupper(key[i])) - 65;
	}
}
